import { createRouter, createWebHistory } from 'vue-router'
import { useRoutesStore } from '@/store/routesStore'
import { useSystemStore } from '@/store/systemStore'

const routes = [
  {
    path: '/',
    redirect: '/layouts/users/list'
  },
  {
    path:"/study",
    name:"study",
    component: ()=> import('@/views/Study.vue')
  },
  {
    path:"/study/add",
    name:"studyadd",
    component: ()=> import('@/views/StudyAdd.vue')
  },
  {
    path:"/study/list",
    name:"studylist",
    component: ()=> import('@/views/StudyList.vue')
  },
  {
    path: '/ls',
    children: [
      {
        path: '/ls/login',
        component: () => import('@/views/login-signin/Login.vue')
      },
      {
        path: '/ls/signin',
        component: () => import('@/views/login-signin/Signin.vue')
      }
    ]
  },
  {
    path: '/layouts',
    name: 'layouts',
    component: () => import('@/views/layouts/Layout.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/404.vue')
  }
]


export const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...routes
  ]
})

router.beforeEach(async (to, from, next) => {
  const systemStore = useSystemStore()
  console.log(systemStore.token);
  const { loadRouteTree, addRoutes, routesTree } = useRoutesStore()
  if (!systemStore.token && to.path !== '/ls/login') {
    next({
      path: '/ls/login'
    })
  }

  else if ( routesTree.length === 0) {
    await loadRouteTree()
    addRoutes()
    next({ ...to })
  }

  else {
    next()
  }
})
